<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');

//打印调试变量
function dd($val, $as_string = false){
	if($as_string){
		return var_export($val);
	}
    var_dump($val);
    exit;
}

//获取当前控制器类名
function fetch_class(){
	$_ci = &get_instance();
	return $_ci->router->class;
}

//获取当前调用方法名
function fetch_method(){
	$_ci = &get_instance();
	return $_ci->router->method;
}

function is_get(){
	return strtolower($_SERVER['REQUEST_METHOD']) === 'get';
}

function is_post(){
	return strtolower($_SERVER['REQUEST_METHOD']) === 'post';
}
function is_xhr(){
    return isset($_SERVER['HTTP_X_REQUESTED_WITH']) &&
    strpos($_SERVER['HTTP_X_REQUESTED_WITH'],'XMLHttpRequest')!==false;
}
function is_email(){

}

function is_phone($phone=''){
    if(preg_match('/^1\d{10}$/',$phone)){
        return true;
    }
    return false;
}

/**
 * 获取客户端IP地址
 * @param integer $type 返回类型 0 返回IP地址 1 返回IPV4地址数字
 * @return mixed
 *
 * @from thinkphp3.2
 */
function get_client_ip($type = 0) {
    $type       =  $type ? 1 : 0;
    static $ip  =   NULL;
    if ($ip !== NULL) return $ip[$type];
    if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
        $arr    =   explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
        $pos    =   array_search('unknown',$arr);
        if(false !== $pos) unset($arr[$pos]);
        $ip     =   trim($arr[0]);
    }elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {
        $ip     =   $_SERVER['HTTP_CLIENT_IP'];
    }elseif (isset($_SERVER['REMOTE_ADDR'])) {
        $ip     =   $_SERVER['REMOTE_ADDR'];
    }
    // IP地址合法验证
    $long = sprintf("%u",ip2long($ip));
    $ip   = $long ? array($ip, $long) : array('0.0.0.0', 0);
    return $ip[$type];
}

function asset($asset_str='', $prefix='', $output=false){
    //相对web根目录
    $asset_name='';
    if(strpos($asset_str, '/')===0){
        $asset_name=$prefix.rtrim($asset_str,'/');
    }
    else{
        //所有的静态资源限定在public目录下
        $asset_name='/public/'.ltrim($prefix,'/').trim($asset_str,'/');
    }

    if($output===true){
        if(strrpos($asset_name, '.js') > 0){
            return "<script src='{$asset_name}'></script>";
        }
        if(strrpos($asset_name, '.css')>0){
            return "<link rel='stylesheet' href='{$asset_name}' type='text/css'>";
        }
    }

    return $asset_name;

}

//override site_url helper for twig
function site_url($uri = '', $protocol = NULL){
    if(strpos($uri, 'http')===0){
        return $uri;
    }
    return get_instance()->config->site_url($uri, $protocol);
}
